package com.xiaomi.eco.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaomi.eco.config.OauchExecutor;
import com.xiaomi.eco.dal.entity.OperateLogEntity;
import com.xiaomi.eco.dal.query.PageResult;
import com.xiaomi.eco.dal.req.TaskDetailReq;
import com.xiaomi.eco.dal.req.TaskEditReq;
import com.xiaomi.eco.dal.req.TaskQueryReq;
import com.xiaomi.eco.dal.res.SearchRes;
import com.xiaomi.eco.dal.res.TaskDetailRes;
import com.xiaomi.eco.dal.res.TaskQueryRes;
import com.xiaomi.eco.dal.entity.DimProductEntity;
import com.xiaomi.eco.mapper.DimProductEntityMapper;
import com.xiaomi.eco.mapper.OFeedbackFlgEntityMapper;
import com.xiaomi.eco.mapper.OperateLogEntityMapper;
import com.xiaomi.eco.service.OFeedbackFlgEntityService;
import com.xiaomi.eco.service.OperateLogEntityService;
import com.xiaomi.eco.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class TaskServiceImpl implements TaskService {

    @Autowired
    private OperateLogEntityMapper operateLogEntityMapper;

    @Autowired
    private OFeedbackFlgEntityMapper oFeedbackFlgEntityMapper;

    @Autowired
    private OperateLogEntityService operateLogEntityService;

    @Autowired
    private OauchExecutor oauchExecutor;

    @Autowired
    private DimProductEntityMapper dimProductEntityMapper;

    @Override
    public PageResult<List<TaskQueryRes>> queryTask(TaskQueryReq taskQueryReq) {
        try {
            if (taskQueryReq.getPageNum() == null || taskQueryReq.getPageSize() == null) {
                taskQueryReq.setPageNum(1);
                taskQueryReq.setPageSize(10);
            }
            Integer pageNum = taskQueryReq.getPageNum();
            Integer pageSize = taskQueryReq.getPageSize();
            PageResult<List<TaskQueryRes>> result = new PageResult<>();
            Page<TaskQueryRes> page = new Page<>(pageNum, pageSize);
            Page<TaskQueryRes> pageList = oFeedbackFlgEntityMapper.queryTaskTotalInfo(taskQueryReq, page);
            if (pageList.getTotal() == 0) {
                return PageResult.success(0, Collections.emptyList());
            }
            result.setTotal(pageList.getTotal());
            result.setList(pageList.getRecords());
            return result;
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new RuntimeException("获取一级任务信息失败");
        }
    }

    @Override
    public PageResult<List<TaskDetailRes>> getTaskDetail(TaskDetailReq taskDetailReq) {
        try {
            if (taskDetailReq.getDate() == null) {
                throw new RuntimeException("参数异常：查询日期不能为空");
            }
            if (taskDetailReq.getPageNum() == null || taskDetailReq.getPageSize() == null) {
                taskDetailReq.setPageNum(1);
                taskDetailReq.setPageSize(10);
            }
            Integer pageNum = taskDetailReq.getPageNum();
            Integer pageSize = taskDetailReq.getPageSize();
            PageResult<List<TaskDetailRes>> result = new PageResult<>();
            Page<TaskDetailRes> page = new Page<>(pageNum, pageSize);
            Page<TaskDetailRes> pageList = oFeedbackFlgEntityMapper.queryTaskDetailInfo(taskDetailReq, page);
            if (pageList.getTotal() == 0) {
                return PageResult.success(0, Collections.emptyList());
            }
            result.setTotal(pageList.getTotal());
            result.setList(pageList.getRecords());
            return result;
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new RuntimeException("获取二级任务信息失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveTask(List<TaskEditReq> taskEditReqList) {
        try {
            if (CollectionUtils.isEmpty(taskEditReqList)) {
                return;
            }
            oFeedbackFlgEntityMapper.batchUpdate(taskEditReqList);

            List<OperateLogEntity> operateLogEntityList = taskEditReqList.stream().map(taskEditReq -> {
                OperateLogEntity operateLogEntity = new OperateLogEntity();
                operateLogEntity.setTaskId(taskEditReq.getId());
                operateLogEntity.setOperateUser(oauchExecutor.getAccount().getUserCode());
                operateLogEntity.setOperateTime(new Date());
                return operateLogEntity;
            }).collect(Collectors.toList());

            List<Long> taskIds = operateLogEntityList.stream().map(OperateLogEntity::getTaskId).collect(Collectors.toList());

            // 查询已存在的taskId
            LambdaQueryWrapper<OperateLogEntity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(OperateLogEntity::getTaskId, taskIds);
            List<OperateLogEntity> existEntities = operateLogEntityService.list(queryWrapper);
            List<Long> existTaskIds = existEntities.stream().map(OperateLogEntity::getTaskId).collect(Collectors.toList());

            // 分离出需要更新的和需要插入的数据
            List<OperateLogEntity> updateList = operateLogEntityList.stream().filter(item -> existTaskIds.contains(item.getTaskId())).collect(Collectors.toList());
            List<OperateLogEntity> insertList = operateLogEntityList.stream().filter(item -> !existTaskIds.contains(item.getTaskId())).collect(Collectors.toList());

            if (!insertList.isEmpty()) {
                operateLogEntityService.saveBatch(insertList);
            }
            if(!updateList.isEmpty()) {
                operateLogEntityMapper.updateBatch(updateList);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<SearchRes> queryL4() {
        QueryWrapper<DimProductEntity> queryWrapper = Wrappers.query();
        queryWrapper.select("distinct cat_lvl4_name,goods_name,model");
        queryWrapper.orderByAsc("cat_lvl4_name,goods_name,model");
        List<DimProductEntity> dimProductEntityList = dimProductEntityMapper.selectList(queryWrapper);
        List<SearchRes> l4List = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(dimProductEntityList)) {
            for (DimProductEntity dimProductEntity : dimProductEntityList) {
                SearchRes searchRes = new SearchRes();
                searchRes.setCatLvl4Name(dimProductEntity.getCatLvl4Name());
                searchRes.setGoodsName(dimProductEntity.getGoodsName());
                searchRes.setModel(dimProductEntity.getModel());
                l4List.add(searchRes);
            }
        }
        return l4List;
    }

    // @Override
    // @Transactional(rollbackFor = Exception.class)
    // public void queryData() {
    //     try {
    //         List<OFeedbackDataEntity> feedbackDataEntityList = oFeedbackDataEntityMapper.queryData();
    //         if (CollectionUtils.isEmpty(feedbackDataEntityList)) {
    //             log.info("无更新数据");
    //         }
    //         List<OFeedbackFlgEntity> feedbackFlgEntityList = new ArrayList<>();
    //         for (OFeedbackDataEntity entity : feedbackDataEntityList) {
    //             OFeedbackFlgEntity flgEntity = new OFeedbackFlgEntity();
    //             BeanUtils.copyProperties(entity, flgEntity);
    //             feedbackFlgEntityList.add(flgEntity);
    //         }
    //         List<List<OFeedbackFlgEntity>> feedFlgList = Lists.partition(feedbackFlgEntityList, 1000);
    //         for (List<OFeedbackFlgEntity> flgEntities : feedFlgList) {
    //             oFeedbackFlgEntityService.saveBatch(flgEntities);
    //         }
    //     } catch (Exception e) {
    //         log.error(e.getMessage());
    //         throw new RuntimeException("数据导入失败");
    //     }
    // }
}
